<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px" size="small">
      <el-form-item label="报修单号" prop="repairCode">
        <el-input
          v-model="queryParams.repairCode"
          placeholder="请输入报修单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input
          v-model="queryParams.equipmentName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报修人" prop="reportPerson">
        <el-input
          v-model="queryParams.reportPerson"
          placeholder="请输入报修人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select 
          v-model="queryParams.status" 
          placeholder="请选择状态" 
          clearable 
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sb:repair:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sb:repair:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="repairList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="报修时间" align="center" prop="reportTime" width="160" />
      <el-table-column label="报修单号" align="center" prop="repairCode" width="150" />
      <el-table-column label="设备编号" align="center" prop="equipmentCode" width="140" />
      <el-table-column label="设备名称" align="center" prop="equipmentName" width="140" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="getStatusType(scope.row.status)"
            size="mini"
          >
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="报修人" align="center" prop="reportPerson" width="100" />
      <el-table-column label="报修人手机号" align="center" prop="reportPhone" width="140">
        <template slot-scope="scope">
          {{ scope.row.reportPhone || '无' }}
        </template>
      </el-table-column>
      <el-table-column label="故障时间" align="center" prop="faultTime" width="160" />
      <el-table-column label="故障描述" align="center" prop="faultDescription" min-width="200" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="230">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['sb:repair:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAccept(scope.row)"
            v-if="scope.row.status === 'pending'"
            v-hasPermi="['sb:repair:edit']"
          >接单</el-button>
          <el-button
            v-if="scope.row.status === 'pending'"
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleCancel(scope.row)"
            v-hasPermi="['sb:repair:edit']"
          >取消维修</el-button>
          <el-button
            v-if="scope.row.status === 'pending'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sb:repair:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 取消维修对话框 -->
    <el-dialog title="取消维修" :visible.sync="cancelOpen" width="500px" append-to-body>
      <el-form ref="cancelForm" :model="cancelForm" label-width="80px">
        <el-form-item label="取消原因" prop="reason">
          <el-input v-model="cancelForm.reason" type="textarea" placeholder="请输入取消原因"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCancel">确 定</el-button>
        <el-button @click="cancelOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRepairApplication, delRepairApplication, acceptRepairApplication, cancelRepairApplication, getRelatedRepairOrder } from "@/api/sb/repairApplication";

export default {
  name: "RepairApplication",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报修单表格数据
      repairList: [],
      // 状态数据字典
      statusOptions: [
        { value: "pending", label: "待接单" },
        { value: "processing", label: "待维修" },
        { value: "repairing", label: "维修中" },
        { value: "completed", label: "已完成" },
        { value: "canceled", label: "已取消" }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        repairCode: null,
        equipmentName: null,
        reportPerson: null,
        status: null
      },
      // 取消维修对话框
      cancelOpen: false,
      // 取消维修表单
      cancelForm: {
        id: null,
        reason: null
      }
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    // 监听路由变化，当从新增页面返回时刷新列表
    this.$watch('$route', (to, from) => {
      if (from.path === '/sb/repair-application/add' && to.path === '/sb/repair-application') {
        console.log('从新增页面返回，刷新列表');
        this.getList();
      }
    });
  },
  methods: {
    /** 查询报修单列表 */
    getList() {
      this.loading = true;
      listRepairApplication(this.queryParams).then(response => {
        console.log("报修单列表数据:", response.rows);
        if (response.rows && response.rows.length > 0) {
          console.log("第一条数据:", JSON.stringify(response.rows[0]));
          console.log("第一条数据的手机号:", response.rows[0].reportPhone);
          
          // 处理数据，确保每条记录都有id和repairId字段
          this.repairList = response.rows.map(item => {
            // 确保每条数据都有id字段(为了兼容)
            if (item.repairId && !item.id) {
              item.id = item.repairId;
            } else if (item.id && !item.repairId) {
              item.repairId = item.id;
            }
            
            // 调试手机号码
            console.log(`报修单 ${item.repairCode} 的报修人: ${item.reportPerson}, 手机号: ${item.reportPhone}`);
            
            return item;
          });
        } else {
          this.repairList = [];
        }
        this.total = parseInt(response.total) || 0;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderCode: null,
        equipmentId: null,
        equipmentName: null,
        equipmentCode: null,
        reportTime: null,
        faultDesc: null,
        faultTime: null,
        reporterId: null,
        reporterName: null,
        reporterPhone: null,
        orderStatus: "1",
        priority: "1",
        faultImages: [],
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.repairId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.replace({ path: '/sb/repair-application/add' });
    },
    /** 查看详情按钮操作 */
    handleView(row) {
      console.log("查看详情按钮点击，当前行数据:", row);
      // 无论是什么ID字段，都转为字符串后传递
      const repairId = row.repairId ? String(row.repairId) : (row.id ? String(row.id) : undefined);
      console.log("将跳转到详情页面，传递ID:", repairId);
      
      if (!repairId) {
        this.$message.error("报修单ID不存在");
        return;
      }
      
      this.$router.push({ path: '/sb/repair-application/detail', query: { id: repairId } });
    },
    /** 接单按钮操作 */
    handleAccept(row) {
      const id = row.repairId || this.ids;
      this.$modal.confirm('是否确认接单？').then(function() {
        return acceptRepairApplication(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("接单成功，报修单状态已更新为处理中");
      }).catch(() => {});
    },
    /** 取消维修按钮操作 */
    handleCancel(row) {
      this.cancelForm = {
        id: row.repairId,
        reason: null
      };
      this.cancelOpen = true;
    },
    /** 提交取消维修 */
    submitCancel() {
      if (!this.cancelForm.reason) {
        this.$message.error("请输入取消原因");
        return;
      }
      cancelRepairApplication(this.cancelForm.id, this.cancelForm.reason).then(response => {
        this.$modal.msgSuccess("取消成功");
        this.cancelOpen = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.repairId || this.ids;
      this.$modal.confirm('是否确认删除报修单编号为"' + (row.orderCode || '') + '"的数据项？').then(function() {
        return delRepairApplication(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 获取状态文本 */
    getStatusText(status) {
      const option = this.statusOptions.find(item => item.value === status);
      return option ? option.label : status;
    },
    /** 获取状态类型 */
    getStatusType(status) {
      switch (status) {
        case 'pending':
          return 'info'; // 待接单
        case 'processing':
          return 'warning'; // 待维修
        case 'repairing':
          return 'primary'; // 维修中
        case 'completed':
          return 'success'; // 已完成
        case 'canceled':
          return 'danger'; // 已取消
        default:
          return 'info';
      }
    }
  }
};
</script> 